<?php
// +----------------------------------------------------------------------
// | zhanshop_mcp / TestAiRagClient.php    [ 2025/8/16 19:28 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\console;

use zhanshop\client\AichatClient;
use zhanshop\client\Httpclient;
use zhanshop\console\Command;
use zhanshop\console\Input;
use zhanshop\console\Output;

class TestAiRagClient extends Command
{
    public function configure()
    {
        $this->useDatabase();
    }

    protected function ragSearch(string $question)
    {
        $client = new Httpclient();
        $data = [
            'database' => 'zhanshop_knowledge',
            'table' => 'xiyouji',
            'question' => $question,
            'limit' => 10
        ];
        $client->setHeader("content-type", "application/json");
        $resp = $client->request("http://192.168.1.5:9021/v1/knowledge/repository", "GET", json_encode($data));
        $data = json_decode($resp['body'], true);
        $document = array_column($data['data'], 'document');
        return implode("\r\n", $document);
    }

    public function execute(Input $input, Output $output)
    {
        $question = "如意金箍棒有多少斤重";
        $ragSearch = $this->ragSearch($question);
        $prompt = '你是一位知识助手，请根据用户的问题和下列片段生成准确的回答。
用户问题: '.$question.'

相关片段:
~~~~~
'.$ragSearch.'
~~~~~
######请基于上述内容作答，不要编造信息。######';
        $aichatClient = new AichatClient('http://192.168.1.5:11434/v1', "123", 'qwen3:8b');
        $aichatClient->systemPrompt($prompt);
        $aichatClient->onMessage(function ($chatClient, $msg){
            echo $msg;
        });

        $aichatClient->send();
    }
}